<script setup>
import {getAiJudgeAndRecommendBySynthesis, getStudyHistory} from "../../../../api/user/user.js";
import {nextTick, ref} from "vue";
import hljs from "highlight.js";
import {ElMessage} from "element-plus";
import {fetchEventSource} from "@microsoft/fetch-event-source";
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import {clearChatHistory} from "@/api/ai/studentChatAIApi.js";
const controller = new AbortController()
const signal = controller.signal;
// 滚动条实例
const scrollbarRef = ref();
// 计数器内部实例
const innerRef = ref();
// 综合评价提示词
let comprehensiveJudgeTip = ref('');
// 综合评价
let comprehensiveJudge = ref('');
let loading = ref(true)
// 本月学习情况
let studyHistory = ref([]);
// 获取对应日期信息
function getDateStudyData(date,index) {
  date = new Date(date.day)
  let now = new Date();
  let nowFirstDay = new Date(now.getFullYear(), now.getMonth(), 1);
  if ( date > now || date < nowFirstDay) {
    return null;
  }
  // 今天的数据还没有所以也不展示
  if ( date.getDate() === now.getDate() ) {
    return null;
  }
  if ( index === 0 ) {
    return studyHistory.value[date.getDate() - 1].videoCount;
  }
  if ( index === 1 ) {
    return studyHistory.value[date.getDate() - 1].practiceCount;
  }
  if ( index === 2 ) {
    return studyHistory.value[date.getDate() - 1].isStudy;
  }
}
function dealAnswer(data,answer) {
  let sseData = data;
  sseData = sseData.replaceAll("&#32;", " ").replaceAll("&#92n", "\n")
  answer += sseData;
  return answer;
}
async function setScrollToBottom() {
  // 注意：需要通过 nextTick 以等待 DOM 更新完成
  await nextTick()
  const max = innerRef.value.clientHeight
  scrollbarRef.value.setScrollTop(max)
}
// 将md转化为html
function mdToHtml(content,callback) {
  import('markdown-it').then(module => {
    const md = module.default('commonmark', {
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre class="hljs"><code>' +
                hljs.highlight(lang, str, true).value +
                '</code></pre>';
          } catch (__) {}
        }

        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    });
    callback(md.render(content));
  });
}
// 用户进入页面时 需要清空和ai对话的历史记录
clearChatHistory();
getAiJudgeAndRecommendBySynthesis().then(res => {
    comprehensiveJudgeTip.value = res.data;
    // fetch请求方法控制器
    let answer = '';
    let nowHtml = '';
    setInterval(async () => {
      if ( nowHtml.length > comprehensiveJudge.value.length ) {
        let nowLen = comprehensiveJudge.value.length;
        if ( nowHtml[nowLen] === '<' ) {
          while ( nowHtml[nowLen] !== '>' ) {
            nowLen ++;
          }
        }
        comprehensiveJudge.value = nowHtml.slice(0,nowLen+1);
        await setScrollToBottom();
      }
    },70)
    fetchEventSource("/api/aiChat/chat?question="+comprehensiveJudgeTip.value,{
      method: 'GET',
      headers: {
        'content-type': 'application/json',
        'token': localStorage.getItem("token")
      },
      signal: signal,
      openWhenHidden: true,
      onmessage(event) {
        answer = dealAnswer(event.data,answer)
        if ( event.data === '&#92n[DONE]') {
          // 发送完成结束对话
          controller.abort();
          return;
        }
        mdToHtml(answer,(html)=>{
          nowHtml = html;
        })
      },
      onclose(event) {
        controller.abort();
      },
      onerror(event) {
        ElMessage.error("对话失败，请重试");
        controller.abort();
      }
    }).catch(err => {
      console.log('抛了一场')
    });
    loading.value = false;
  }
)
getStudyHistory().then(res => {
  studyHistory.value = res.data;
  console.log(studyHistory)
})
onBeforeRouteLeave((to, from, next) => {
  controller.abort()
  next()
})
onBeforeRouteUpdate((to, from, next) => {
  controller.abort()
  next()
})
</script>

<template>
  <div class="common-area">
    <el-container class="container-area">
      <div class="study-calendar">
        <el-calendar v-if="studyHistory.length > 0" class="calendar">
          <template #header="{ date }">
            <span><strong>本月学习记录</strong></span>
          </template>
          <template #date-cell="{ data }">
            <p :class="getDateStudyData(data,2) === 1 ? 'is-selected' : ''">
              {{ data.day.split('-').slice(1).join('-') }}
              <span v-if="getDateStudyData(data,2) != null">
                {{ getDateStudyData(data,2) ? '✔️' : '❌'  }}
                <div v-if="getDateStudyData(data,2) === 1">
                  <div class="tips">📺当日共观看<strong>{{getDateStudyData(data,0)}}</strong>个视频</div>
                  <div class="tips">📏当日共练习<strong>{{getDateStudyData(data,1)}}</strong>道题目</div>
                </div>
              </span>
            </p>
          </template>
        </el-calendar>
        <el-divider direction="vertical" class="divider"></el-divider>
      </div>
        <div
            v-loading="loading"
            element-loading-text="Loading..."
            class="ai-judge">
          <div class="ai-title">📚AI综合评价结果如下：</div>
          <el-scrollbar ref="scrollbarRef" always>
            <div ref="innerRef">
          <div v-html="comprehensiveJudge"></div>
            </div>
          </el-scrollbar>
        </div>
    </el-container>
  </div>
</template>

<style scoped lang="less">
.container-area {
  width: 100%;
  height: 100%;
  display: flex;
  .study-calendar {
    width: 70%;
    height: 100%;
    display: flex;
    .calendar {
      height: 100%;
    }
    .tips {
      font-size: 10px;
      color: gray;
    }
    .divider {
      height: 100%;
    }
  }
  .ai-judge {
    flex: 1;
    overflow-y: scroll;
    .ai-title {
      font-weight: bold;
      margin-top: 13px;
      width: 100%
    }
  }
}
.is-selected {
  color: #1989fa;
}
</style>